package queue;

public class LoopQueue<E> {
    private E data[];
    private int front;
    private int tail;

    public LoopQueue(int capacity) {
        data = (E[]) (new Object[capacity]);
        front = 0;
        tail = 0;
    }

    public LoopQueue() {
        this(10);
    }

    public int getCapacity() {
        return data.length - 1;
    }

    public int getSize() {
        return (tail - front + data.length) % data.length;
    }

    public boolean isEmpty() {
        return front == tail;
    }

    public E deQueue() {
        if (front == tail) {
            throw new IllegalArgumentException("Queue is empty");
        }

        E res = data[front];
        data[front] = null;
        front = (front + 1) % data.length;

        if (getSize() < getCapacity() / 4) {
            resize(getCapacity() / 2);
        }

        return res;

    }

    public void enQueue(E e) {
        if ((tail + 1) % data.length == front) {
            resize(data.length * 2);
        }

        data[tail] = e;
        tail = (tail + 1) % data.length;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) (new Object[newCapacity]);
        for (int i = 0; i < getSize(); i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = getSize();

    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("队列的长度：");
        stringBuilder.append(getSize() + "\t");
        stringBuilder.append("队列的容量：");
        stringBuilder.append(getCapacity());
        stringBuilder.append("\nfront [");
        for (int i = front; i < tail; i = (i + 1) % data.length) {
            stringBuilder.append(data[i]);
            if ((i + 1) % data.length != tail) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append("] tail");
        return stringBuilder.toString();
    }
}
